import { SendOutlined } from '@ant-design/icons';
import { Button, Input, Tooltip, message } from 'antd';
import {
  MutableRefObject,
  PropsWithChildren,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
  useImperativeHandle,
  forwardRef,
  useCallback,
} from 'react';
import PromptBot from './prompt-bot';
import DocUpload from '../chat/doc-upload';
import DocList from '../chat/doc-list';
import { IDocument } from '@/types/knowledge';
import { ChatContext } from '@/app/chat-context';
import { apiInterceptors, getDocumentList } from '@/client/api';
import { SendSvg } from '../icons';
import TextArea from 'antd/es/input/TextArea';
import IatRecorder from '@/utils/iatRecorder';
import { set, values } from 'lodash';
import Recorder from './recorder';
type TextAreaProps = Omit<Parameters<typeof Input.TextArea>[0], 'value' | 'onPressEnter' | 'onChange' | 'onSubmit'>;

interface Props {
  loading?: boolean;
  onSubmit: (val: string) => void;
  handleFinish?: (val: boolean) => void;
  handleIsRecorder: (val: boolean) => void;
  updateTempMsg: (val: any) => void;
  handleIsTempMsg: (val: boolean) => void;
}

const CompletionInput = (
  { children, loading, onSubmit, handleFinish, handleIsRecorder, updateTempMsg, handleIsTempMsg, ...props }: PropsWithChildren<Props & TextAreaProps>,
  ref: any,
) => {
  useImperativeHandle(ref, () => ({
    insertUserInput: (val: string) => {
      console.log(val);
      val && setUserInput(val);
    },
  }));

  const { dbParam, scene } = useContext(ChatContext);

  const [userInput, setUserInput] = useState('');
  const showUpload = useMemo(() => scene === 'chat_knowledge', [scene]);
  const [documents, setDocuments] = useState<IDocument[]>([]);
  const uploadCountRef = useRef(0);
  const [recorderFlag, setRecorderFlag] = useState(false);
  const textAreaRef = useRef(null);
  /* const initIat = ()=>{}  */
  // @ts-ignore
  /* const iatRecorder = new IatRecorder({
    onWillStatusChange: (status, oldstatus) => {
      console.log(iatRecorder);
      console.log({ status });
      console.log({ oldstatus });
      if (status === 'end') {
        document.getElementsByClassName('recorder')[0].style.display = 'block';
        document.getElementsByClassName('recorder')[1].style.display = 'none';
        document.getElementById('soundWave').style.display = 'none';
        if (iatRecorder.resultText) {
          setUserInput(() => iatRecorder.resultText);
          onSubmit(iatRecorder.resultText);
          setUserInput('');
        }
      }
      if (status === 'init') {
        document.getElementsByClassName('recorder')[0].style.display = 'none';
        document.getElementsByClassName('recorder')[1].style.display = 'block';
        document.getElementById('soundWave').style.display = 'flex';
        handleIsRecorder(true);
      }
    },
    onWillResultTextTemp: (newValue: any) => {

    },
  }); */
  const play = () => {
    /*  connectWebSocket(); */
  };
  useEffect(() => {
    showUpload && fetchDocuments();
    textAreaRef?.current.focus();
  }, [dbParam]);
  async function fetchDocuments() {
    if (!dbParam) {
      return null;
    }
    const [_, data] = await apiInterceptors(
      getDocumentList(dbParam, {
        page: 1,
        page_size: uploadCountRef.current,
      }),
    );
    setDocuments(data?.data!);
  }
  const handleRecorder = useCallback(
    (e: any) => {
      /* iatRecorder.start() */
      if (!recorderFlag) {
        /* console.log(1) */
        /* setRecorderFlag(true) */
      } else {
        /* console.log(2)
      iatRecorder.stop() */
        /* setUserInput(iatRecorder.resultText) */
        /* setRecorderFlag(false) */
      }
    },
    [recorderFlag],
  );

  /* const start = () => {
    if (!loading) {
      iatRecorder.start();
    } else {
      message.error('录音打开失败正在请求数据中');
    }
  }; */

  /* const stop = () => {
    if (!loading) {
      iatRecorder.stop();
    } else {
      message.error('录音打开失败正在请求数据中');
    }
  }; */
  /* function throttle(fn:Function,time:any){
    let timer:any = null;
    return function (){
      if(!timer){
        timer = setTimeout(function(){
          fn(iatRecorder.resultText)
          timer = null
        },time)
      }
    }
  } */
  useEffect(() => {
    let isSpacePressing = false;
    document.addEventListener('keydown', function (event) {
      if (event.key === ' ' && !loading && !isSpacePressing) {
        isSpacePressing = true;
        /* throttle(start,100) */
        /* start() */
        // 长按开始，执行相应的操作
        console.log('空格键被长按');
      }
    });
    document.addEventListener('keyup', function (event) {
      if (event.key === ' ' && !loading && isSpacePressing) {
        isSpacePressing = false;
        // 长按结束，执行相应的操作
        /* stop() */
        console.log('空格键长按结束');
      }
    });
  }, []);
  /*  const close = ()=>{
    console.log(iatRecorder)
    console.log(iatRecorder.status)
    console.log(iatRecorder.status)
    iatRecorder.stop()
    console.log(iatRecorder);
    console.log(iatRecorder.resultText)
  } */
  const onUploadFinish = () => {
    uploadCountRef.current += 1;
    fetchDocuments();
  };
  const handleUserInput = (value: any) => {
    /* setTimeout(() => {

    }, 500); */
    setUserInput(() => value);
  };
  // TODO: 修改输入框样式
  return (
    <div style={{ width: '100%' }}>
      <div className="flex-1 relative" style={{ height: '100%', alignItems: 'center', display: 'flex' }}>
        <DocList documents={documents} dbParam={dbParam} />
        {/* <button onClick={start} id='recorder' set-data='recorderFlag'>
        {recorderFlag ? '取消' : '录音'}
      </button> */}

        {/* <button onClick={close}>
        取消
      </button> */}
        {showUpload && <DocUpload handleFinish={handleFinish} onUploadFinish={onUploadFinish} className="absolute z-10 top-2 left-2" />}
        <Input.TextArea
          className={`flex-1 ${showUpload ? 'pl-10' : ''} pr-10 custom-textarea`}
          style={{
            backgroundColor: 'transparent',
            border: 'none',
            color: '#fff',
            fontSize: 'calc(18vw * var(--w))',
            height: '100%',
            borderRadius: 'calc(16vh * var(--h))',
          }}
          size="large"
          value={userInput}
          ref={textAreaRef}
          placeholder="请输入..."
          autoSize={{ minRows: 1, maxRows: 4 }}
          {...props}
          onPressEnter={(e) => {
            if (!userInput.trim()) return;
            if (e.keyCode === 13) {
              if (e.shiftKey) {
                setUserInput((state) => state + '\n');
                return;
              }
              onSubmit(userInput);
              setTimeout(() => {
                setUserInput('');
              }, 0);
            }
          }}
          onChange={(e) => {
            if (typeof props.maxLength === 'number') {
              setUserInput(e.target.value.substring(0, props.maxLength));
              return;
            }
            // debugger;
            setUserInput(e.target.value);
          }}
        />

        {/* { <PromptBot
        submit={(prompt) => {
          setUserInput(userInput + prompt);
        }}
      />} */}
        {children}
      </div>
      <div className="flex sendMeesge">
        {/* <div className="soundWave" id="soundWave" style={{ display: 'none' }}>
          <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
          <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
          <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
          <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
          <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
          <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
          <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
          <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
          <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
        </div> */}
        {/* <Tooltip placement="left" title="点击说话" arrow={true} defaultOpen={true} color="#486180" overlayClassName="myTooltip">
          <img
            onClick={start}
            className="recorder"
            set-status="start"
            src="../recorderStart.png"
            alt=""
            style={{ width: 'calc(23.75vw * var(--w))', height: 'calc(30vh * var(--h))' }}
          />
          <img
            onClick={stop}
            className="recorder"
            set-status="stop"
            src="../recorderIng.png"
            alt=""
            style={{ width: 'calc(30vw * var(--w))', height: 'calc(30vh * var(--h))', display: 'none' }}
          />
        </Tooltip> */}
        {
          <Recorder
            loading={loading}
            handleIsRecorder={handleIsRecorder}
            handleUserInput={handleUserInput}
            onSubmit={onSubmit}
            updateTempMsg={updateTempMsg}
            handleIsTempMsg={handleIsTempMsg}
          />
        }
        {
          <Button
            className="ml-2 flex items-center justify-center absolute right-0 bottom-1"
            style={{
              color: '#fff',
              background: 'linear-gradient( 90deg, #62F1FF 0%, #2371F1 100%)',
              width: 'calc(102vw * var(--w))',
              height: 'calc(40vh * var(--h))',
              border: 'none',
              position: 'relative',
              top: '1px',
            }}
            size="middle"
            type="text"
            shape="round"
            loading={loading}
            icon={<SendSvg />}
            onClick={() => {
              onSubmit(userInput);
              setTimeout(() => {
                setUserInput('');
              }, 0);
            }}
          >
            发送
          </Button>
        }
        <span id="text12"></span>
      </div>
    </div>
  );
};

export default forwardRef(CompletionInput);
